from fastapi import APIRouter, Depends

from core.security import get_current_user_m
from db.mysql.users import Users
from db.pydantic.request.template import TemplateCreateRequest, BindTemplateRequest
from services.template_service import TemplateService, get_template_service
from utils.result import Result

router = APIRouter()

@router.get("/api/templates")
async def get_templates(service: TemplateService = Depends(get_template_service),current_user: Users = Depends(get_current_user_m)):
    """
    获取模板列表 验证用户身份信息，返回所有的模板列表
    """
    result = service.get_template(current_user)
    if result:
        return Result.success(result)
    return Result.fail(msg="获取模板列表失败")

@router.post("/api/templates")
async def create_template(req: TemplateCreateRequest, service: TemplateService = Depends(get_template_service),current_user: Users = Depends(get_current_user_m)):
    """
    创建模板
    """
    result = service.create_template(req,current_user)
    if result:
        return Result.success(result)
    return Result.fail(msg="创建模板失败")

@router.put("/api/templates/{template_id}")
async def update_template(template_id: int, req: TemplateCreateRequest, service: TemplateService = Depends(get_template_service),current_user: Users = Depends(get_current_user_m)):
    """
    更新模板
    """
    result = service.update_template(template_id, req,current_user)
    if result:
        return Result.success(result)
    return Result.fail(msg="更新模板失败")

@router.delete("/api/templates/{template_id}")
async def delete_template(template_id: int, service: TemplateService = Depends(get_template_service),current_user: Users = Depends(get_current_user_m)):
    """
    删除模板
    """
    result = service.delete_template(template_id,current_user)
    if result:
        return Result.success(result)
    return Result.fail(msg="删除模板失败")

@router.post("/api/devices/{device_phone}/bind-template")
async def bind_template(device_phone: str,req: BindTemplateRequest, service: TemplateService = Depends(get_template_service),current_user: Users = Depends(get_current_user_m)):
    """
    绑定模板
    """
    result = service.bind_template(device_phone,req,current_user)
    if result:
        return Result.success(result)
    return Result.fail(msg="绑定模板失败")

@router.get("/api/devices/{device_phone}/config")
async def get_device_config(device_phone: str, service: TemplateService = Depends(get_template_service),current_user: Users = Depends(get_current_user_m)):
    """
    获取设备配置
    """
    result = service.get_device_config(device_phone,current_user)
    if result:
        return Result.success(result)
    return Result.fail(msg="获取设备配置失败")